/*
 * Copyright (C) 2012 Jesse Webb (gweebz@gmail.com)
 *
 * This file is part of Gwahtzee.
 *
 * Gwahtzee is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gwahtzee is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Gwahtzee.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.googlecode.gwahtzee.model;

import java.util.*;

public class ScoreSheet {
    public static final List<Cell> Cells;

    private static final int GWAHTZEE_VALUE = 50;

    private UpperSection upperSection;
    private LowerSection lowerSection;

    static {
        Cells = new ArrayList<Cell>();
        Cells.add(Cell.Aces);
        Cells.add(Cell.Twos);
        Cells.add(Cell.Threes);
        Cells.add(Cell.Fours);
        Cells.add(Cell.Fives);
        Cells.add(Cell.Sixes);
        Cells.add(Cell.ThreeOfAKind);
        Cells.add(Cell.FourOfAKind);
        Cells.add(Cell.FullHouse);
        Cells.add(Cell.SmallStraight);
        Cells.add(Cell.LargeStraight);
        Cells.add(Cell.Chance);
        Cells.add(Cell.Gwahtzee);
    }

    public ScoreSheet() {
        this.upperSection = new UpperSection();
        this.lowerSection = new LowerSection();
    }

    public UpperSection getUpperSection() {
        return upperSection;
    }

    public LowerSection getLowerSection() {
        return lowerSection;
    }

    public int getTotalScore() {
        return getUpperSection().getTotal() + getLowerSection().getTotal();
    }

    public boolean isComplete() {
        return getUpperSection().isComplete() && getLowerSection().isComplete();
    }

    public class UpperSection {
        private Integer aces;
        private Integer twos;
        private Integer threes;
        private Integer fours;
        private Integer fives;
        private Integer sixes;

        public Integer getAces() {
            return aces;
        }

        public Integer getTwos() {
            return twos;
        }

        public Integer getThrees() {
            return threes;
        }

        public Integer getFours() {
            return fours;
        }

        public Integer getFives() {
            return fives;
        }

        public Integer getSixes() {
            return sixes;
        }

        public int getSubTotal() {
            int acesScore = aces != null ? aces : 0;
            int twosScore = twos != null ? twos : 0;
            int threesScore = threes != null ? threes : 0;
            int foursScore = fours != null ? fours : 0;
            int fivesScore = fives != null ? fives : 0;
            int sixesScore = sixes != null ? sixes : 0;
            return acesScore + twosScore + threesScore + foursScore + fivesScore + sixesScore;
        }

        public boolean isBonusEarned() {
            return getSubTotal() >= 63;
        }

        public int getBonus() {
            return isBonusEarned() ? 35 : 0;
        }

        public int getTotal() {
            return getSubTotal() + getBonus();
        }

        public boolean isComplete() {
            return !(aces == null || twos == null || threes == null || fours == null || fives == null || sixes == null);
        }

        public int checkAcesScore(Dice dice) {
            return calculateCellScore(dice, 1);
        }

        public int checkTwosScore(Dice dice) {
            return calculateCellScore(dice, 2);
        }

        public int checkThreesScore(Dice dice) {
            return calculateCellScore(dice, 3);
        }

        public int checkFoursScore(Dice dice) {
            return calculateCellScore(dice, 4);
        }

        public int checkFivesScore(Dice dice) {
            return calculateCellScore(dice, 5);
        }

        public int checkSixesScore(Dice dice) {
            return calculateCellScore(dice, 6);
        }

        public void scoreAces(Dice dice) {
            if (aces != null) throw new IllegalStateException("Aces has already been scored");
            aces = checkAcesScore(dice);
            getLowerSection().incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreTwos(Dice dice) {
            if (twos != null) throw new IllegalStateException("Twos has already been scored");
            twos = checkTwosScore(dice);
            getLowerSection().incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreThrees(Dice dice) {
            if (threes != null) throw new IllegalStateException("Threes has already been scored");
            threes = checkThreesScore(dice);
            getLowerSection().incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreFours(Dice dice) {
            if (fours != null) throw new IllegalStateException("Fours has already been scored");
            fours = checkFoursScore(dice);
            getLowerSection().incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreFives(Dice dice) {
            if (fives != null) throw new IllegalStateException("Fives has already been scored");
            fives = checkFivesScore(dice);
            getLowerSection().incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreSixes(Dice dice) {
            if (sixes != null) throw new IllegalStateException("Sixes has already been scored");
            sixes = checkSixesScore(dice);
            getLowerSection().incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        private int calculateCellScore(Dice dice, int cell) {
            int score = 0;
            for (Die die : dice) {
                if (die.getFaceValue() == cell) score += cell;
            }
            return score;
        }

        private boolean isCellScored(int cell) {
            switch (cell) {
                case 1:
                    return aces != null;
                case 2:
                    return twos != null;
                case 3:
                    return threes != null;
                case 4:
                    return fours != null;
                case 5:
                    return fives != null;
                case 6:
                    return sixes != null;
                default:
                    throw new IllegalArgumentException("Unrecognized cell: " + cell);
            }
        }
    }

    public class LowerSection {
        private Integer threeOfAKind;
        private Integer fourOfAKind;
        private Integer fullHouse;
        private Integer smallStraight;
        private Integer largeStraight;
        private Integer chance;
        private Integer gwahtzee;
        private int bonusGwahtzeeCount;

        public Integer getThreeOfAKind() {
            return threeOfAKind;
        }

        public Integer getFourOfAKind() {
            return fourOfAKind;
        }

        public Integer getFullHouse() {
            return fullHouse;
        }

        public Integer getSmallStraight() {
            return smallStraight;
        }

        public Integer getLargeStraight() {
            return largeStraight;
        }

        public Integer getChance() {
            return chance;
        }

        public Integer getGwahtzee() {
            return gwahtzee;
        }

        public int getBonusGwahtzeeCount() {
            return bonusGwahtzeeCount;
        }

        public int getBonusGwahtzeeScore() {
            return (bonusGwahtzeeCount * 100);
        }

        public int getTotal() {
            int threeOfAKindScore = threeOfAKind != null ? threeOfAKind : 0;
            int fourOfAKindScore = fourOfAKind != null ? fourOfAKind : 0;
            int fullHouseScore = fullHouse != null ? fullHouse : 0;
            int smallStraightScore = smallStraight != null ? smallStraight : 0;
            int largeStraightScore = largeStraight != null ? largeStraight : 0;
            int chanceScore = chance != null ? chance : 0;
            int gwahtzeeScore = gwahtzee != null ? gwahtzee : 0;
            return threeOfAKindScore + fourOfAKindScore + fullHouseScore + smallStraightScore + largeStraightScore +
                    chanceScore + gwahtzeeScore + (bonusGwahtzeeCount * 100);
        }

        public boolean isComplete() {
            return !(threeOfAKind == null || fourOfAKind == null || fullHouse == null ||
                    smallStraight == null || largeStraight == null || chance == null || gwahtzee == null);
        }

        public int checkThreeOfAKindScore(Dice dice) {
            int score = 0;
            if (validXxxOfAKind(dice, 3)) score = dice.getTotal();
            return score;
        }

        public int checkFourOfAKindScore(Dice dice) {
            int score = 0;
            if (validXxxOfAKind(dice, 4)) score = dice.getTotal();
            return score;
        }

        public int checkFullHouseScore(Dice dice) {
            int score = 0;
            if (validFullHouse(dice)) score = 25;
            return score;
        }

        public int checkSmallStraightScore(Dice dice) {
            int score = 0;
            if (validStraight(dice, 4) || validJoker(dice)) score = 30;
            return score;
        }

        public int checkLargeStraightScore(Dice dice) {
            int score = 0;
            if (validStraight(dice, 5) || validJoker(dice)) score = 40;
            return score;
        }

        public int checkChanceScore(Dice dice) {
            return dice.getTotal();
        }

        public int checkGwahtzeeScore(Dice dice) {
            int score = 0;
            if (validXxxOfAKind(dice, 5)) score = GWAHTZEE_VALUE;
            return score;
        }

        public void scoreThreeOfAKind(Dice dice) {
            if (threeOfAKind != null) throw new IllegalStateException("ThreeOfAKind has already been scored");
            threeOfAKind = checkThreeOfAKindScore(dice);
            incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreFourOfAKind(Dice dice) {
            if (fourOfAKind != null) throw new IllegalStateException("FourOfAKind has already been scored");
            fourOfAKind = checkFourOfAKindScore(dice);
            incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreFullHouse(Dice dice) {
            if (fullHouse != null) throw new IllegalStateException("FullHouse has already been scored");
            fullHouse = checkFullHouseScore(dice);
            incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreSmallStraight(Dice dice) {
            if (smallStraight != null) throw new IllegalStateException("SmallStraight has already been scored");
            smallStraight = checkSmallStraightScore(dice);
            incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreLargeStraight(Dice dice) {
            if (largeStraight != null) throw new IllegalStateException("LargeStraight has already been scored");
            largeStraight = checkLargeStraightScore(dice);
            incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreChance(Dice dice) {
            if (chance != null) throw new IllegalStateException("Chance has already been scored");
            chance = checkChanceScore(dice);
            incrementBonusGwahtzeeCountIfApplicable(dice);
        }

        public void scoreGwahtzee(Dice dice) {
            if (gwahtzee != null) throw new IllegalStateException("Gwahtzee has already been scored");
            gwahtzee = checkGwahtzeeScore(dice);
        }

        private boolean validXxxOfAKind(Dice dice, int xxx) {
            Map<Integer, Integer> valueToFrequencyMap = new HashMap<Integer, Integer>();
            for (Die die : dice) {
                int faceValue = die.getFaceValue();
                int frequency = valueToFrequencyMap.get(faceValue) == null ? 1 : valueToFrequencyMap.get(faceValue) + 1;
                valueToFrequencyMap.put(faceValue, frequency);
            }
            for (Integer frequency : valueToFrequencyMap.values()) {
                if (frequency >= xxx) return true;
            }
            return false;
        }

        private boolean validFullHouse(Dice dice) {
            boolean validFullHouse = false;
            int[] faceValues = new int[dice.size()];
            for (int i = 0; i < dice.size(); i++) {
                faceValues[i] = dice.get(i).getFaceValue();
            }
            Arrays.sort(faceValues);
            if ((faceValues[0] == faceValues[1] && faceValues[1] == faceValues[2] && faceValues[3] == faceValues[4]) ||
                    (faceValues[0] == faceValues[1] && faceValues[2] == faceValues[3] && faceValues[3] == faceValues[4])) {
                validFullHouse = true;
            }
            return validFullHouse;
        }

        private boolean validJoker(Dice dice) {
            boolean validJoker = false;
            if (gwahtzee != null && validXxxOfAKind(dice, 5)) {
                if (getUpperSection().isCellScored(dice.get(0).getFaceValue())) {
                    validJoker = true;
                }
            }
            return validJoker;
        }

        private boolean validStraight(Dice dice, int numSequentialRequired) {
            Set<Integer> uniqueValues = new HashSet<Integer>();
            for (Die die : dice) {
                uniqueValues.add(die.getFaceValue());
            }
            Integer[] sortedUniqueValues = uniqueValues.toArray(new Integer[uniqueValues.size()]);
            Arrays.sort(sortedUniqueValues);
            int largestStraight = 0;
            int currentStraight = 0;
            Integer previous = null;
            for (Integer i : sortedUniqueValues) {
                if (previous != null) {
                    if (i == previous + 1) {
                        currentStraight++;
                        if (currentStraight > largestStraight) {
                            largestStraight = currentStraight;
                        }
                    } else {
                        currentStraight = 1;
                    }
                } else {
                    currentStraight = 1;
                }
                previous = i;
            }
            return largestStraight >= numSequentialRequired;
        }

        private void incrementBonusGwahtzeeCountIfApplicable(Dice dice) {
            if (gwahtzee != null && gwahtzee == GWAHTZEE_VALUE && validXxxOfAKind(dice, 5)) bonusGwahtzeeCount += 1;
        }
    }

    public enum Cell {
        Aces,
        Twos,
        Threes,
        Fours,
        Fives,
        Sixes,
        ThreeOfAKind,
        FourOfAKind,
        FullHouse,
        SmallStraight,
        LargeStraight,
        Chance,
        Gwahtzee
    }
}
